#include <myheader.h>
#define BUF_SIZE 5
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t producer_cond = PTHREAD_COND_INITIALIZER;
static pthread_cond_t consumer_cond = PTHREAD_COND_INITIALIZER;

static int buf[BUF_SIZE];
static int count = 0;
void* consumer3_func(void* arg){
    for(int i = 0; i < 10; i++){

    pthread_mutex_lock(&mutex);
    while(count == 0){
        //缓冲区为空，等待缓冲区有数据
        pthread_cond_wait(&consumer_cond,&mutex);
    }
        int item = buf[--count];
        printf("consumer3: %d\n",item);
        //通知消费者写数据
        //pthread_cond_signal(&producer_cond);
        pthread_cond_broadcast(&producer_cond);
    pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
void* consumer2_func(void* arg){
    for(int i = 0; i < 10; i++){

    pthread_mutex_lock(&mutex);
    while(count == 0){
        //缓冲区为空，等待缓冲区有数据
        pthread_cond_wait(&consumer_cond,&mutex);
    }
        int item = buf[--count];
        printf("consumer2: %d\n",item);
        //通知消费者写数据
        //pthread_cond_signal(&producer_cond);
        pthread_cond_broadcast(&producer_cond);
        //pthread_cond_signal(&producer_cond);
    pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
void* consumer1_func(void* arg){
    for(int i = 0; i < 10; i++){

    pthread_mutex_lock(&mutex);
    while(count == 0){
        //缓冲区为空，等待缓冲区有数据
        pthread_cond_wait(&consumer_cond,&mutex);
    }
        int item = buf[--count];
        printf("consumer1: %d\n",item);
        //通知消费者写数据
        //pthread_cond_signal(&producer_cond);
        pthread_cond_broadcast(&producer_cond);
    pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
void* producer_func(void* arg){
    sleep(2);
    for(int i = 0; i < 30; i++){

    pthread_mutex_lock(&mutex);
    while(count == BUF_SIZE){
        //缓冲区满，等待消费者读取数据
        pthread_cond_wait(&producer_cond,&mutex);
    }
    buf[count++] = i;
    //通知消费者读取数据
    //pthread_cond_signal(&consumer_cond);
    pthread_cond_broadcast(&consumer_cond);
    pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
/*Usage:  */
int main(int argc, char *argv[])
{

    //consumer and producer
    pthread_t consumer1,consumer2,consumer3,producer;
    pthread_create(&consumer1,NULL,consumer1_func,NULL);
    pthread_create(&consumer3,NULL,consumer3_func,NULL);
    pthread_create(&consumer2,NULL,consumer2_func,NULL);
    pthread_create(&producer,NULL,producer_func,NULL);
    pthread_join(consumer1,NULL);
    pthread_join(consumer2,NULL);
    pthread_join(consumer3,NULL);
    pthread_join(producer,NULL);




    return 0;
}

